package edu.ajou.scw;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class FindMember
 */
@WebServlet("/FindMember")
public class FindMember extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindMember() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String targetId = request.getParameter("id");
		String exact = request.getParameter("exact");
		
		DatabaseConnector conn = new DatabaseConnector();
		
		boolean bExact;
		
		if (exact != null)
			bExact = true;
		else
			bExact = false;
		
		ArrayList<UserInfo> ui = conn.getUserInfo(targetId, bExact);
		
		JSONObject result = new JSONObject();
		JSONArray members = new JSONArray();
		
		if (ui != null)
		{
			Log.d("Finding Member: " + targetId);
			for (int i=0; i<ui.size(); i++)
			{
				JSONObject person = new JSONObject();
				UserInfo user = ui.get(i);
				
				person.put("id", user.getId());
				person.put("name", user.getName());
				person.put("email", user.getEmail());
				person.put("image", user.getImage());
				members.add(person);
			}
		}
		
		result.put("members", members);
		
		PrintWriter writer = response.getWriter();
		
		writer.write(result.toJSONString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
